import cgi
import logging
import datetime
from db_model import GadgetFiles
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp



class GetFile(webapp.RequestHandler):
  
  def get(self, filename):
    query = GadgetFiles.Query()
    filenameStr = "%s" % filename
    query.filter('Name', filenameStr)
    file = query.get()
    if (query.count() == 0):
      self.error(404)
      self.response.out.write("File <b>%s</b> not found!<br>" % filename)
      self.response.out.write("<a href='/StaticFile/Edit/%s' >Care to create it?</a>" % filename)
      
      return
    
    value = file.Data
      
    expires_date = datetime.datetime.utcnow() - datetime.timedelta(1)
    expires_str = expires_date.strftime("%d %b %Y %H:%M:%S GMT")
    self.response.headers.add_header("Expires", expires_str)
    self.response.out.write("%s" % value)


    
class EditFile(webapp.RequestHandler):
  
  def _auth(self):
    if not users.GetCurrentUser():
      self.redirect(users.create_login_url(self.request.uri))
      return False
  
    if not users.IsCurrentUserAdmin():
      self.response.out.write("Hello %s!<br>" % users.GetCurrentUser().email())
      self.response.out.write('You must be an admin to view this page.<br>')
      self.response.out.write("<a href='%s'>logout</a>" % users.create_logout_url(self.request.uri))
      return False
    
    return True
  
  def _displayForm(self, filename):
    query = GadgetFiles.Query()

    filenameStr = "%s" % filename
    query.filter('Name', filenameStr)
    file = query.get()
     
    value = ""
    if (query.count()!= 0):
      value=file.Data
    
    self.response.out.write("Filename: <b>%s</b><br>" % filename)
    self.response.out.write("<form method='POST'>")
    self.response.out.write("Value: <br><textarea name='data' rows='30' cols='100'>")
    self.response.out.write("%s" % value)
    self.response.out.write("</textarea><br>")
    self.response.out.write("<input value='submit' type='submit' >")
    self.response.out.write("</form>")
  
  def post(self, filename):
    if (not self._auth()): return
    if (filename == ""):
      self.response.out.write("Missing filename")
      return
    
    data = self.request.get("data")
    query = GadgetFiles.Query()
    if (query.count() == 0):
      file = GadgetFiles()
    else:
      file = query.get()
    
    file.Name = filename
    file.Data = db.Text(data)
    file.put()
   
    self._displayForm(filename)
    
  def get(self, filename):
    if (not self._auth()): 
      return
    
    if (filename == ""):
      query = GadgetFiles.Query()
      if (query.count() == 0):
        self.response.out.write("No files!")
        return
      self.response.out.write("Files here:<br>")
      self.response.out.write("<table border=1>")
      self.response.out.write("<tr><th>Filename</th><th>Date</th></tr>")      
      for file in query :
        self.response.out.write("<tr><td><a href='%s'>%s</a></td><td>%s</td></tr>" % (self.request.uri+file.Name, file.Name, file.TimeStamp))

      self.response.out.write("</table>")
    else :
      self._displayForm(filename)